function [ctc, prt, stimdata] = importfif(outfile, cspec, fiffile)
% importfif  - import FIF file
%
% FORMAT:       [ctc, prt, sdata] = importfif(outfile, cspec [, fiffile])
%
% Input fields:
%
%       outfile     CTC output filename (may include path)
%       cspec       condition specification (used for
%                   PRT::ImportStimChannels, if not given, no PRT created)
%       fiffile     FIF filename, interactively if not given or empty
%
% Output fields:
%
%        ctc        CTC object
%        prt        PRT object
%        sdata      stimulation data from FIF::CreateCTC method

% Version:  v0.7c
% Build:    7100320
% Date:     Oct-03 2007, 8:31 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
   ~ischar(outfile) || ...
    isempty(outfile)
    error( ...
        'BVQXtools:BadArguments', ...
        'Bad or missing argument.' ...
    );
end
outfile = outfile(:)';
[outp{1:3}] = fileparts(outfile);
if isempty(outp{1})
    outp{1} = '.';
end
if ~strcmpi(outp{3}, '.ctc')
    outfile = [outp{1} '/' outp{2} '.ctc'];
end
if nargin < 2 || ...
   ~isstruct(cspec) || ...
    isempty(cspec) || ...
   ~isfield(cspec, 'Name') || ...
   ~isfield(cspec, 'Color') || ...
   ~isfield(cspec, 'Pattern') || ...
   ~isfield(cspec, 'Duration')
    cspec = [];
else
    cspec = cspec(:)';
end
if nargin < 3 || ...
   ~ischar(fiffile) || ...
    isempty(fiffile) || ...
    exist(fiffile(:)', 'file') ~= 2
    fiffile = '*.fif';
end

% set transiosize of CTC
fif = BVQXfile(fiffile);
fif.ReadInfoHeaders;

% get number of channels
noc = fif.Value('NrOfSensorChannels');

% fill channel specification
chspec = struct;
chspec.ExpList = sort([1:3:noc, 2:3:noc]);
chspec.StimAuto = true;

% create CTC and get stim data
[ctc, stimdata] = fif.CreateCTC(outfile, chspec);

% write positional data
fif.WritePOS([outp{1} '/' outp{2} '.pos'], chspec.ExpList);
fif.WriteSFH([outp{1} '/' outp{2} '.sfh']);

% FIF no longer needed
fif.ClearObject;

% create protocol
if ~isempty(cspec)
    prt = BVQXfile('new:prt');

    % import stimulus channels
    prt.ImportStimChannels(stimdata, ctc.SamplingFrequency, cspec);

    % save PRT
    prt.SaveAs([outp{1} '/' outp{2} '.prt']);

    % keep protocol ?
    if nargout < 2
        prt.ClearObject;
    else
        bless(prt, 1);
    end
    
% no protocol
else
    prt = [];
end

% keep CTC open
if nargout < 1
    ctc.ClearObject;
else
    bless(ctc, 1);
end
